import os
from ctypes import byref, c_buffer, WinDLL
import api, core, mouseHandler, screenBitmap, winUser, ui
from contentRecog import recogUi, RecogImageInfo
from .abstract import ContentRecognizer
selfDir = os.path.dirname(__file__)
try:
    dll = WinDLL(os.path.join(selfDir, "..", "bin", "OCR_X86.dll"))
except OSError:
    dll = None
# 滑块验证识别器类
class VSlideRecognizer(ContentRecognizer):
    def imgRecog(self, imgData, online = False):
        # 识别 开始
        if online:
            return self.post('http://39.99.235.101:7003/ocr', imgData)
        if not dll:
            return -1
        res = c_buffer(100)
        if dll.ocr(imgData, len(imgData), byref(res)):
            return res.value.decode()
        return -1
    # 识别接口
    def onRecog(self, imgData):
        with open(r'g:\temp\xcc\im.bmp', 'wb') as f:
            f.write(imgData)
        # imgData: 带有文件头部信息的二进制位图数据
        res = self.imgRecog(imgData, True)
        if isinstance(res, int) and res < 0:
            raise Exception(_('No result.'))
        l, t, r, b = res.split(',')
        return [
            [{'x': int(l), 'y': int(t), 'width': int(r) -int(l), 'height': int(b) -int(t), 'text': '缺口'}]
        ]
    def onCancel(self):pass
    def start(self):
        obj = api.getNavigatorObject()
        location = obj.location
        x, y = location.left + location.width // 2, location.top + location.height // 2
        self.move(x, y)
        attr = obj.IA2Attributes.values()
        if 'gt_refresh_button' in attr:
            self.click()
            def find():
                parent = obj.parent
                print('\n'.join(parent.devInfo))
                self.move(x, y + location.height)
                core.callLater(1000, self.verify, parent)
            core.callLater(1000, find)
            return
        if 'geetest_slider_button' in attr:
            core.callLater(1000, self.verify, obj.parent)
    def verify(self, parent):
        obj = api.getMouseObject()
        if not 'class' in obj.IA2Attributes.keys():return
        attr = obj.IA2Attributes['class']
        if (not 'gt_slider_knob' in attr) and (not 'geetest_slider_button' in attr):
            ui.message(_('请先定位到滑块附近'))
            return
        if not self.validateObject(parent):return
        location = parent.location
        if not self.validateCaptureBounds(location):return
        try:
            imgInfo = RecogImageInfo.createFromRecognizer(location.left, location.top, location.width, location.height, self)
        except ValueError:
            ui.message(_("Content is not visible"))
            return
        ui.message(_("Recognizing"))
        sb = screenBitmap.ScreenBitmap(imgInfo.recogWidth, imgInfo.recogHeight)
        pixels = sb.captureImage(location.left, location.top, location.width, location.height)
        def callback(result):
            res = result.words[0]
            l, t, w, h = res.left, res.top, res.width, res.height
            self.hold(l)
        self.recognize(pixels, imgInfo, callback)
    def click(self):
        mouseHandler.executeMouseEvent(winUser.MOUSEEVENTF_LEFTDOWN, 0, 0)
        mouseHandler.executeMouseEvent(winUser.MOUSEEVENTF_LEFTUP, 0, 0)
    def move(self, x, y):
        winUser.setCursorPos(x, y)
        mouseHandler.executeMouseMoveEvent(x, y)
    def hold(self, targetX):
        x, y = winUser.getCursorPos()
        direction = x < targetX
        def slide():
            nonlocal x
            if (direction and x > targetX) or ((not direction) and x < targetX):
                self.move(int(x), y)
                mouseHandler.executeMouseEvent(winUser.MOUSEEVENTF_LEFTUP, 0, 0)
                return
            self.move(int(x), y)
            j = api.getMouseObject()
            ui.message(f'{j.location.left}')
            ui.message(j.IA2Attributes['class'])
            if direction:
                x += 15 -((x / targetX) * 10)
            else:
                x -= 15 -((targetX / x) * 10)
            core.callLater(20, slide)
        mouseHandler.executeMouseEvent(winUser.MOUSEEVENTF_LEFTDOWN, 0, 0)
        slide()
